/*
@(#)MenuController   2024-11-07
 
Copyright (c) 2011-2024 杭州湖畔网络技术有限公司 
保留所有权利 
本软件为杭州湖畔网络技术有限公司所有及包含机密信息，须遵守其相关许可证条款进行使用。
Copyright (c) 2011-2024 HUPUN Network Technology CO.,LTD.
All rights reserved.
This software is the confidential and proprietary information of HUPUN
Network Technology CO.,LTD("Confidential Information").  You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with HUPUN.
Website：http://www.hupun.com
*/
package org.obp.upms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.obp.core.result.ApiResult;
import org.obp.data.utils.ObjectUtils;
import org.obp.upms.context.SecurityHolder;
import org.obp.upms.context.WorkUserHolder;
import org.obp.upms.domain.request.RoleResourceParam;
import org.obp.upms.domain.response.ResourceTreeVO;
import org.obp.upms.domain.response.UserResourceVO;
import org.obp.upms.model.WorkRoleResourceDO;
import org.obp.upms.service.WorkRoleResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Jackey 2024/11/7
 */
@RestController
@RequestMapping("/v1/work/resource")
@Api(tags = {"资源接口"})
public class ResourceController {

    @Autowired
    private WorkUserHolder workUserHolder;
    @Autowired
    private SecurityHolder securityHolder;
    @Autowired
    private WorkRoleResourceService workRoleResourceService;

    @ApiOperation("用户资源列表")
    @GetMapping("/list")
    public ApiResult<List<UserResourceVO>> resourceList() {

        String userID = workUserHolder.getCurrentUserID();

        List<WorkRoleResourceDO> userResourceDOS = workRoleResourceService.getResourcesByUserId(userID);

        return ApiResult.ok(ObjectUtils.copyList(userResourceDOS, UserResourceVO.class));
    }

    @ApiOperation("角色资源列表")
    @GetMapping("/list/byRole")
    public ApiResult<List<ResourceTreeVO>> resourceListByRole(String roleId) {

        List<ResourceTreeVO> resourceTreeVOS = SecurityHolder.getResourceTree();

        List<WorkRoleResourceDO> roleResourceDOS = workRoleResourceService.getResourcesByRoleId(roleId);
        List<String> urlKeys = roleResourceDOS.stream()
                .map(i -> SecurityHolder.ResourceRoleMeta.buildUrlKey(i.getUrlMethod(), i.getUrlPath())).collect(Collectors.toList());

        for (ResourceTreeVO resourceTreeVO : resourceTreeVOS) {
            resourceTreeVO.getChildren().forEach(i -> i.setPermit(urlKeys.contains(SecurityHolder.ResourceRoleMeta.buildUrlKey(i.getUrlMethod(), i.getUrlPath()))));
        }

        return ApiResult.ok(resourceTreeVOS);
    }

    @ApiOperation("资源绑定角色")
    @PostMapping("/bind/role")
    public ApiResult<String> resourceBindRole(@RequestBody RoleResourceParam param) {

        List<WorkRoleResourceDO> oldRelations = workRoleResourceService.lambdaQuery()
                .eq(WorkRoleResourceDO::getRoleId, param.getRoleId()).list();
        if (CollectionUtils.isEmpty(oldRelations)) return ApiResult.ok();

        List<String> paramUrls = param.getUrls().stream()
                .map(r -> r.getUrlMethod() + "-" + r.getUrlPath()).collect(Collectors.toList());
        List<String> oldUrls = oldRelations.stream()
                .map(r -> r.getUrlMethod() + "-" + r.getUrlPath()).collect(Collectors.toList());

        for (RoleResourceParam.ResourceUrlParam paramItem : param.getUrls()) {
            String paramUrl = paramItem.getUrlMethod() + "-" + paramItem.getUrlPath();
            if (oldUrls.contains(paramUrl)) continue;
            WorkRoleResourceDO workRoleResource = new WorkRoleResourceDO();
            workRoleResource.setRoleId(param.getRoleId());
            workRoleResource.setUrlMethod(paramItem.getUrlMethod());
            workRoleResource.setUrlPath(paramItem.getUrlPath());
            workRoleResourceService.save(workRoleResource);
            securityHolder.refreshResourceRoleMeta(paramItem.getUrlMethod(), paramItem.getUrlPath());
        }

        for (WorkRoleResourceDO oldItem : oldRelations) {
            String oldUrl = oldItem.getUrlMethod() + "-" + oldItem.getUrlPath();
            if (paramUrls.contains(oldUrl)) continue;
            workRoleResourceService.remove(new QueryWrapper<WorkRoleResourceDO>().lambda()
                    .eq(WorkRoleResourceDO::getRoleId, param.getRoleId())
                    .eq(WorkRoleResourceDO::getUrlMethod, oldItem.getUrlMethod())
                    .eq(WorkRoleResourceDO::getUrlPath, oldItem.getUrlPath()));
            securityHolder.refreshResourceRoleMeta(oldItem.getUrlMethod(), oldItem.getUrlPath());
        }

        return ApiResult.ok();
    }

    @ApiOperation("资源解绑角色")
    @PostMapping("/unbind/role")
    public ApiResult<String> resourceUnbindRole(@RequestBody RoleResourceParam param) {
        for (RoleResourceParam.ResourceUrlParam url : param.getUrls()) {
            workRoleResourceService.remove(new QueryWrapper<WorkRoleResourceDO>().lambda()
                    .eq(WorkRoleResourceDO::getRoleId, param.getRoleId())
                    .eq(WorkRoleResourceDO::getUrlMethod, url.getUrlMethod())
                    .eq(WorkRoleResourceDO::getUrlPath, url.getUrlPath()));
            securityHolder.refreshResourceRoleMeta(url.getUrlMethod(), url.getUrlPath());
        }
        return ApiResult.ok();
    }

}